<?php if ( ! defined('ABSPATH')) exit('restricted access');
/*
	Plugin Name: Find a Doctor
	Plugin URI: http://www.wpnukes.com/plugins/find-a-doctor/
	Description: A built-in wpnukes plugin to manage doctors
	Author: wpnukes
	Version: 1.0 
	Author URI: http://www.wpnukes.com/
*/

class wpnukes_doctors
{
	var $slug = 'nukes_doctors';
	var $apslug = 'nukes_appointments';
 	var $text_domain = 'nukes_doctors';
	
	function __construct()
	{
		/** Plugin Base URL */
		$this->baseurl = plugin_dir_url( __FILE__ );

		/** Plugin Path */
		$this->path = plugin_dir_path( __FILE__ );
		
		if(!is_admin())	add_action( 'wp_print_scripts', array($this, 'front_scripts'));
		if( ! is_admin()) return;
		/** Register Activation hook */
		register_activation_hook( __FILE__, array($this, 'create_table') );
		
		/** Language Support */
		load_plugin_textdomain( $this->text_domain, false, $this->path . '/languages/' );
		
		/** Admin menu */
		add_action('admin_menu', array($this, 'admin_menu'));
		
		/** Load Scripts and Styles */
		add_action( 'admin_print_scripts', array($this, 'admin_script'));
		add_action( 'admin_print_styles', array($this, 'admin_style'));
		
		//Ajax Callback
		add_action('wp_ajax_doctor_fields', array($this, 'doctor_fields'));
		
		/** User page hooks */
		add_action('personal_options_update', array($this, 'save_fields'));
		add_action('edit_user_profile_update', array($this, 'save_fields'));
		
		/** Redirect User to Add doctors enteries */
		add_action('admin_init', array($this, 'redirect_after_user_add'));
		
		add_action('deleted_user', array($this, 'user_delete_init'));
		
		add_shortcode('doctor_form', array($this, 'search_form_shortcode'));
		add_shortcode('appointment_form', array($this, 'appointment_form')); /**Code by coder 3.2.0 */
		
		//add_action('nuke_save_appointment', array($this, 'save_appointment')); /**Code by coder 3.2.0 */
	}
	
	
	function create_table()
	{
		global $wpdb;

		$query = "CREATE TABLE IF NOT EXISTS `".$wpdb->prefix."appointments` (
		  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
		  `requested_phy` bigint(20) NOT NULL,
		  `app_type` varchar(25) NOT NULL,
		  `other_type` varchar(25) NOT NULL,
		  `patient_name` varchar(25) NOT NULL,
		  `app_name` varchar(100) NOT NULL,
		  `app_gender` enum('male','female') NOT NULL,
		  `app_dob` datetime NOT NULL,
		  `street_address` varchar(150) NOT NULL,
		  `app_city` varchar(60) NOT NULL,
		  `app_state` varchar(100) NOT NULL,
		  `app_zip` varchar(6) NOT NULL,
		  `day_phone` varchar(20) NOT NULL,
		  `evening_phone` varchar(20) NOT NULL,
		  `app_email` varchar(40) NOT NULL,
		  `request_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
		  `status` tinyint(4) NOT NULL DEFAULT '0',
		  `appointment_date` datetime NOT NULL,
		  `description` mediumtext NOT NULL,
		  `seen_before` varchar(4) NOT NULL DEFAULT '0',
		  `existing` varchar(4) NOT NULL DEFAULT '0',
		  `refering_phy` varchar(20) NOT NULL,
		  `phy_address` varchar(150) NOT NULL,
		  `session_ip` varchar(16) NOT NULL,
		  `session_time` datetime NOT NULL,
		  
		  PRIMARY KEY (`ID`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;";
		
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($query);
	}
	
	
	function admin_script()
	{
		if(is_admin())
		{
			if($GLOBALS['pagenow'] == 'user-new.php' || $GLOBALS['pagenow'] == 'user-edit.php'){
				wp_enqueue_media();
				wp_enqueue_script('find-a-doctor', $this->baseurl . 'js/script.js');
			}
			if(isset($_GET['page']) && $_GET['page'] == 'nukes_appointments' && $GLOBALS['pagenow'] == 'admin.php')
			{ /**Code by coder 3.2.0 */
				wp_enqueue_script('jquery-timepicker', $this->baseurl . 'js/timepicker.js', array('jquery-ui-datepicker','wp-color-picker'));
				wp_enqueue_script('doctor-appointment_picker', $this->baseurl . 'js/script.js');
			}
		}
	}
	
	function front_scripts()
	{
		wp_enqueue_script('jquery-timepicker', $this->baseurl . 'js/timepicker.js', array('jquery-ui-slider','jquery-ui-datepicker'), '', true);
		wp_enqueue_style('jquery-timepicker', $this->baseurl. 'css/timepicker.css', array('wp-color-picker'));
	}
	
	function admin_style()
	{
		if(is_admin())
		{
			/**Code by coder 3.2.0 */
			if($GLOBALS['pagenow'] == 'user-new.php' || $GLOBALS['pagenow'] == 'user-edit.php')
				wp_enqueue_style('media-upload');
			if(isset($_GET['page']) && $_GET['page'] == 'nukes_appointments' && $GLOBALS['pagenow'] == 'admin.php')
			{
				wp_enqueue_style('jquery-timepicker', $this->baseurl. 'css/timepicker.css');
			}
		}
	}
	
	/**Code by coder 3.2.0 */
	 function save_appointment($data)
	{
		global $wpdb;
		$this->_webnukes = &$GLOBALS['_webnukes']; /** Clone the fw_base_class object */
		if(count($data['requested_phy']))
		{

			$current_time = date('Y:m:d h:i:s');
			$query = $wpdb->get_row("SELECT ID, session_ip, session_time FROM ".$wpdb->prefix."appointments WHERE session_ip ='".$_SERVER['REMOTE_ADDR']."' AND session_time > '".$current_time."' ORDER BY ID DESC");
			
			if($query) {
				echo '<div class="block1" style="width:93%;"> 
								<img alt="" src="'.get_template_directory_uri().'/images/error.png" style="margin:0 9px 0 0;height:19px;"> 
								<strong>'.__('Error', $this->text_domain).'</strong> - '.__('You can submit this form after 10 minutes from previous submission', $this->text_domain).'
							</div>';
				return;
			}

		
			/** Include the configuration file */
			require($this->basepath() . 'config/appointment_fields.php');
					
			//print_r($options);exit;
			foreach($options as $k=>$v)
			{
				$this->_webnukes->validation->set_rules($k, $v['label'], $v['validation']);
			}
			
			$this->_webnukes->validation->run();
			if($this->_webnukes->validation->run() !== false)
			{
				$settings = array();
				
				foreach($options as $k=>$v)
				{
					$settings[$k] = $this->_webnukes->validation->post($k);
				}
				$settings['session_ip'] = $_SERVER['REMOTE_ADDR'];
				$settings['session_time'] = date('Y:m:d h:i:s', strtotime("+10 minutes"));

				//$_SESSION['doctor_'.$ip] = strtotime("+5 minutes"); /**Store the current time against the user IP */
				$GLOBALS['wpdb']->insert($GLOBALS['wpdb']->prefix.'appointments', $settings);

				echo '<div class="block1" style="width:93%;"> 
						<img alt="" src="'.get_template_directory_uri().'/images/success.png" style="margin:0 9px 0 0;height:19px;"> 
						<strong>'.__('SUCCESS', $this->text_domain).'</strong> - '.__('You Request is recieved Successfully', $this->text_domain).'
					</div>';
				
			}else{
				/** Get the array of errors */
				$errors = (!is_array($this->_webnukes->validation->_error_array)) ? array($this->_webnukes->validation->_error_array) : $this->_webnukes->validation->_error_array ;
				/** Prepare errors HTML to show on frontend */
				$messages = '';
				foreach($errors as $k=>$message)
				{
					echo '<div class="block1" style="width:93%;"> 
							<img alt="" src="'.get_template_directory_uri().'/images/error.png" style="margin:0 9px 0 0;height:19px;"> 
							<strong>'.__('Error', $this->text_domain).'</strong> - '.$message.'
						</div>';
				}
			}
		}
	}
	
	function basepath()
	{
		return plugin_dir_path( __FILE__ );
	}
	
	function load_files()
	{
		/** Our class extends the WP_List_Table class, so we need to make sure that it's there */
		require_once(ABSPATH . 'wp-admin/includes/template.php' );
		
		if( ! class_exists('WP_Screen') )
			require_once( ABSPATH . 'wp-admin/includes/screen.php' );
		
		if(!class_exists('WP_List_Table'))
			require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
	}
	
	function doctors_list()
	{
		/** Load wordpress supported files */
		$this->load_files();

		/** Include the configuration file */
		require_once($this->basepath() . 'config/doctors_fields.php');
		require_once('handlers/doctors.php');
		
		$list_table = new doctors_List_Table($this->text_domain);
	}
	
	function appointments_list()
	{
		$this->doctors_array();
		/** Load wordpress supported files */
		$this->load_files();

		/** Include the configuration file */
		require_once($this->basepath() . 'config/appointment_fields.php');			
		require_once('handlers/appointments.php');

		$list_table = new appointment_List_Table($options, $this->text_domain);
	}
	
	function doctors_array()
	{
		$doctors = get_users('role=doctors');
		$return = array();
		foreach($doctors as $doctor)
		{
			$return[$doctor->ID] = $doctor->display_name;
		}
		
		return $return;
	}
	
	function admin_menu()
	{
		/** Check if the current user can view doctor informaiton */
		if(current_user_can('create_users') || current_user_role() == 'doctors')
		{
			if(current_user_can('create_users'))
			{
				add_menu_page( __('Find a Doctor', $this->text_domain), __('Doctors', $this->text_domain), 'manage_options', 'nukes_doctors', array($this, 'doctors_list'), $this->baseurl.'/images/doctor-icon.png');
				add_submenu_page( __('nukes_doctors', $this->text_domain), __('Appointments', $this->text_domain), __('Appointments', $this->text_domain), 'edit_posts', 'nukes_appointments', array($this, 'appointments_list'));
			}elseif(current_user_role() == 'doctors')
			{//printr(current_user_can());
				add_menu_page( __('Appointments', $this->text_domain), __('Appointments', $this->text_domain), 'read', 'nukes_appointments', array($this, 'appointments_list'));
			}
		}
	}
	
	function doctor_fields($user)
	{
		/** Return if the user is not logged In */
		if( ! is_numeric($_POST['user_id'])) return;
		
		$user_id = $_POST['user_id'];
	
		/** Allow admin and user itself to edit the info */
		$sameuser = ($user_id == get_current_user_id()) ? true : false;
		
		if(current_user_can('create_users') || $sameuser)
		{
			$settings = get_user_meta($user_id);
	
			$_webnukes = $GLOBALS['_webnukes'];
			$_webnukes->load('html_class', '', true); /** Load WPnukes HTML class */
			$_webnukes->load('wp_html_class','html'); /** Load wordpress HTML class */
			
			/** Include the configuration file */
			require_once($this->path . 'config/doctors_fields.php');
			
			$data = array();
			foreach($options as $k=>$v)
			{
				$value = (isset($settings[$k])) ? array($k=>$settings[$k][0]) : array($k=>$v['std']);
				$data['fields'][$k] = $_webnukes->html->generator($k, $v, $value, 'array');
			}
			
			echo '<h3>' . __('Doctor Info', $this->text_domain) . '</h3>';
			$_webnukes->html->layout('wp_admin/form_table', $data);
			die($_webnukes->html->build());
		}
	}
	
	function save_fields($user_id)
	{
		global $wpdb;
		if ( ! current_user_can( 'edit_user', $user_id ) || $_POST['role'] != 'doctors') return false;
		
		require_once($this->basepath() . 'config/doctors_fields.php');

		$wpdb->update($wpdb->prefix."users", array('user_status'=>1), array('ID'=>$_POST['user_id']));

		//@TODO: user input validation
		$data = array();
		foreach($options as $k=>$v)
		{
			if( ! empty($_POST[$k]))
			{
				if(get_user_meta($user_id, $k, true) === false) add_user_meta($user_id, $k, $_POST[$k], true);
				else update_usermeta($user_id, $k, $_POST[$k]);
			}
		}
		
		//exit(wp_redirect(self_admin_url('admin.php?page='.$this->slug)));
	}
	
	function redirect_after_user_add()
	{
		if(!empty($_GET['id']) && !empty($_GET['update']) && ($_GET['update'] == 'add'))
		{
			$userid = $_GET['id'];
			$user = get_userdata( $userid );
			wp_redirect( admin_url("/user-edit.php?user_id=".$user->ID) );
		}
	}
	
	function user_delete_init($user)
	{
		if(isset($_GET['role']) && $_GET['role'] == 'doctors')
		wp_redirect( self_admin_url('admin.php?page='.$this->slug) );
		exit;
	}
	
	function search_form_shortcode($atts, $content = null)
	{
		extract( shortcode_atts( array(
			'url' => ''
		), $atts ) );
		
		return $this->search_form('', $url);
	}
	
	function search_form($tpl = '', $url = '')
	{
		$_webnukes = $GLOBALS['_webnukes'];
		$_webnukes->load('html_class', '', true); /** Load WPnukes HTML class */
		$_webnukes->load('wp_html_class','html'); /** Load wordpress HTML class */

		/** Include the configuration file */
		require_once($this->path . '/config/search_fields.php');

		foreach($options as $k=>$v)
		{
			$value = array($k=>$v['std']);
			$data['fields'][$k] = $_webnukes->html->generator($k, $v, $value, 'array');
		}
		
		$data['url'] = ($url) ? $url : '';
		//echo '<h3>' . __('Find a Doctor', THEME_NAME) . '</h3>';
		$tpl = ($tpl) ? $tpl : 'doctors/plugin_doctor_form' ;
		return $_webnukes->html->layout($tpl, $data, true);
	}
	
	function custom_query($query)
	{
		global $wpdb;
		
		$sql = "SELECT ".$wpdb->prefix."usermeta.meta_value FROM ".$wpdb->prefix."usermeta WHERE ".$wpdb->prefix."usermeta.meta_key = '".$query."'";//echo $sql;exit;
	
		$results = $wpdb->get_results($sql, ARRAY_A);

		$res = array();
		$res['0'] = __('Select Value', $this->text_domain);
		foreach($results as $k=>$v)
		{
			$res[$v['meta_value']] = ucwords(str_replace(array('-', '_'), ' ', $v['meta_value']));
		}
		
		return (array) $res;
	}
	
	function appointment_form($atts, $content = null)
	{
		global $options;
		extract( shortcode_atts( array(
			'last' => ''
		), $atts ) );
		return $this->app_form();
	}
	
	
	function app_form($tpl = '', $opt = false)
	{
		$_webnukes = $GLOBALS['_webnukes'];
		$_webnukes->load('html_class', '', true); /** Load WPnukes HTML class */
		$_webnukes->load('wp_html_class','html'); /** Load wordpress HTML class */
		
		/** Include the configuration file */
		require_once($this->basepath() . 'config/appointment_fields.php');			
		
		$tpl = ($tpl) ? $tpl : 'doctors/plugin_appointment_form' ;

		if($opt) {	
			$data['fields'] = $options;
			return $_webnukes->html->layout($tpl, $data, true);
		}
		
		foreach($options as $k=>$v)
		{
			$value = (isset($_POST) && count($_POST)) ? $_POST: array($k=>$v['std']);
			$data['fields'][$k] = $_webnukes->html->generator($k, $v, $value, 'array');
			if(isset($v['heading']) && !empty($v['heading'])) $data['fields'][$k]['heading'] = $v['heading'];
		}
		
		echo '<h3>' . __('Request an Appointment', $this->text_domain) . '</h3>';
		
		return $_webnukes->html->layout($tpl, $data, true);
	}
	
}

$wpnukes = new wpnukes_doctors;